package com.demo.login;

import com.demo.common.model.SystemUser;
import com.jfinal.aop.Before;
import com.jfinal.mvc.Controller;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.session.SessionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by lan_cyl on 2016/11/29.
 */
public class LoginController extends Controller {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);
    private static final String LOGIN_URL = "/login";
    private static final String MAIN_URL = "/blog/1";

    public void index() {

        if (SystemUser.dao.authenticated()) {
            // 调转到主页面
            this.redirect(MAIN_URL);
        } else {
            // 显示登录页
            this.createToken("loginToken");
            this.render("login.html");
        }
    }

    @Before(LoginValidator.class)
    public void login() {
        try {
            SystemUser.dao.login(this.getPara("username"), this.getPara("password"));

            // 调转到主页面
            this.redirect(MAIN_URL);
            return;
        } catch (LockedAccountException e) {
            LOGGER.error(e.getMessage());
            this.setAttr("msg", "账号已被锁定");
        } catch (AuthenticationException e) {
            LOGGER.error(e.getMessage());
            this.setAttr("msg", "用户名或者密码错误");
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            this.setAttr("msg", "系统异常");
        }
        this.keepPara("username");
        this.forwardAction(LOGIN_URL);
    }

    public void logout() {
        try {
            SystemUser.dao.logout();

            this.redirect(LOGIN_URL);
        } catch (SessionException ise) {
            LOGGER.debug("Encountered session exception during logout.  This can generally safely be ignored.", ise);
        } catch (Exception e) {
            LOGGER.debug("登出发生错误", e);
        }
    }
}
